﻿using System;
using Newtonsoft.Json;

namespace Simple.Common
{
    /// <summary>
    /// 通用的扩展方法
    /// </summary>
    public static class ObjectExt
    {
        /// <summary>
        /// 转换为Json字符
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJson( this object obj )
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize<T>(this string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 是否为空字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        /// <summary>
        /// 字符转换为时间，如果不成功返回 null
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime? ToDateTime(this string datetime)
        {
            DateTime d;
            if (DateTime.TryParse(datetime, out d))
            {
                return d;
            }
            return null;
        }

        /// <summary>
        /// 字符转换为整数
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static int ToInt(this string number)
        {
            int i;
            int.TryParse(number, out i);
            return i;
        }
    }
}
